<template>
  <div>
    <div style="text-align: end; margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="handleBindPrams">
          <template #icon>
            <icon-link />
          </template>
          绑定参数
        </a-button>
      </a-space>
    </div>
    <a-spin :loading="data.loading">
      <a-table :data="data.tableData" :columns="data.columns" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #status="{ record }">
          <template v-if="record.status === 1">
            <a-tag color="green">已启用</a-tag>
          </template>
          <template v-else>
            <a-tag color="red">已停用</a-tag>
          </template>
        </template>
        <template #action="{ record }">
          <a-space>
            <template v-if="record.status === 1">
              <a-button type="text" size="small" status="warning" @click="handleRunComplex(record, false, getList)">
                <template #icon>
                  <icon-stop />
                </template>
                停用
              </a-button>
            </template>
            <template v-else>
              <a-button type="text" size="small" status="success" @click="handleRunComplex(record, true, getList)">
                <template #icon>
                  <icon-play-arrow />
                </template>
                启用
              </a-button>
            </template>
            <a-button type="text" size="small" @click="handleBindParamsUpdata(record)"> 修改 </a-button>
            <a-button type="text" status="danger" size="small" @click="handleBindParamsDelete(record)"> 删除 </a-button>
          </a-space>
        </template>
      </a-table>
      <a-pagination
        :total="data.pagination.total"
        :current="data.pagination.pageStart"
        :page-size="data.pagination.pageLength"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      ></a-pagination>
    </a-spin>
    <a-modal
      v-if="data.bindVisible"
      title="绑定参数"
      v-model:visible="data.bindVisible"
      width="700px"
      @before-ok="handleBindParamsOk"
    >
      <a-form :model="data.form" ref="formRef">
        <a-form-item label="模板" field="modelId" :rules="[{ required: true, message: '请选择模板' }]">
          <!-- <a-select v-model="data.form.templateName" placeholder="请选择">
            <a-option
              v-for="item in data.thresholdList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select> -->
          <div class="flex flex-col">
            <a-input-search
              style="border-radius: 15px; margin-bottom: 5px; width: 200px"
              placeholder="输入可筛选模板名称"
              size="small"
              v-model="tableSearch"
            />
            <a-table
              style="width: 100%"
              size="small"
              :scroll="{
                maxHeight: '300px'
              }"
              :columns="columns"
              row-key="id"
              :data="data.thresholdList.filter((item) => item.name.indexOf(tableSearch) > -1)"
              :row-selection="rowSelection"
              @select="handleSelect"
              :selected-keys="data.selectedKeys"
              :pagination="false"
              align="center"
            >
            </a-table>
          </div>
        </a-form-item>
        <a-form-item label="参数">
          <a-select
            value-key="paramId"
            multiple
            allow-search
            allow-clear
            placeholder="请选择"
            v-model="data.form.paramList"
          >
            <a-option v-for="item in paramsList" :key="item.id" :value="item" :label="item.paramName"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="运行模式">
          <a-radio-group v-model="data.form.runMode">
            <a-radio :value="1">运行一次后参数置空</a-radio>
            <a-radio :value="2">周期运行</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="间隔时间" v-if="data.form.runMode === 2">
          <a-input-number v-model="data.form.intervalTime" :min="0">
            <template #append>秒</template>
          </a-input-number>
        </a-form-item>
        <!-- <a-form-item label="算法执行模式">
          <a-radio-group v-model="data.form.mode">
            <a-radio :value="1">根据时间段</a-radio>
            <a-radio :value="2">根据条件</a-radio>
          </a-radio-group>
        </a-form-item>
        <template v-if="+data.form.mode === 1">
          <template v-for="(item, index) in data.form.bindTimes" :key="index">
            <a-form-item label="生效时间">
              <a-radio-group v-model="data.form.bindTimes[index].state">
                <a-radio :value="1">生效</a-radio>
                <a-radio :value="0">不生效</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-range-picker
                  v-model="data.form.bindTimes[index].time"
                  show-time
                />
                <a-button type="primary" @click="addTime()">
                  <template #icon>
                    <icon-plus />
                  </template>
                </a-button>
                <a-button
                  v-if="data.form.bindTimes.length > 1"
                  @click="deleteTime(index)"
                >
                  <template #icon>
                    <icon-minus />
                  </template>
                </a-button>
              </a-space>
            </a-form-item>
          </template>
        </template> -->
        <a-form-item label="正常值上限">
          <a-input v-model="data.form.upperLimit" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="正常值下限">
          <a-input v-model="data.form.lowerLimit" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="告警级别">
          <a-select v-model="data.form.alarmLevel" placeholder="请选择">
            <a-option :value="1">1</a-option>
            <a-option :value="2">2</a-option>
            <a-option :value="3">3</a-option>
            <a-option :value="4">4</a-option>
            <a-option :value="5">5</a-option>
            <a-option :value="6">6</a-option>
            <a-option :value="7">7</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { apiTemplate } from '@/api/complexModel'
import { handleRunComplex } from '@/views/algorithmBinding/bind/api'
const tableSearch = ref('')
const props = defineProps({
  deviceId: {
    type: String,
    default: ''
  },
  paramsList: {
    type: Array,
    default: () => []
  },
  currentSatellite: {
    type: Object,
    default: () => {}
  }
})

const rowSelection = {
  type: 'radio'
}

const columns = [
  {
    title: '模板名称',
    dataIndex: 'name'
  },
  {
    title: '执行方法名',
    dataIndex: 'methodName'
  },
  {
    title: '镜像名称',
    dataIndex: 'imageName'
  },
  {
    title: '备注',
    dataIndex: 'description'
  }
]

const data = reactive({
  loading: false,
  tableData: [],
  satelitesList: [],
  columns: [
    {
      title: '序号',
      slotName: 'index',
      width: 60,
      customRender: ({ index }) => {
        return index + 1 + (data.pagination.pageStart - 1) * data.pagination.pageLength
      }
    },
    {
      title: '模板名称',
      dataIndex: 'modelName'
    },
    // {
    //   title: "算法执行模式",
    //   dataIndex: "mode",
    //   render: ({ record }) => {
    //     return +record.mode === 1 ? "根据时间段" : "根据条件";
    //   },
    // },
    {
      title: '运行模式',
      dataIndex: 'runMode',
      render: ({ record }) => {
        return +record.runMode === 1 ? '运行一次后参数置空' : '周期运行'
      }
    },
    {
      title: '上限',
      dataIndex: 'upperLimit'
    },
    {
      title: '下限',
      dataIndex: 'lowerLimit'
    },
    {
      title: '告警等级',
      dataIndex: 'alarmLevel',
      render: ({ record }) => {
        return record.alarmLevel + '级'
      }
    },
    {
      title: '运行状态',
      dataIndex: 'status',
      slotName: 'status'
    },
    // { title: "级别", dataIndex: "alarmLevel" },
    // { title: "创建时间", dataIndex: "createDate" },
    { title: '操作', slotName: 'action', width: 150 }
  ],
  satelliteId: null,
  selectedKeys: [],
  pagination: {
    total: 0,
    pageStart: 1,
    pageLength: 10
  },
  bindVisible: false,
  form: {
    runMode: 1,
    mode: 1,
    bindTimes: [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  },
  thresholdList: [],
  templateFlag: 0
})
const formRef = ref(null)

const handleBindParamsUpdata = (record) => {
  apiTemplate.getParamBindById(record.id).then((res) => {
    if (res.code === 200) {
      data.bindVisible = true
      data.form = res.data
      data.form.modelId = res.data.modelId
      data.selectedKeys = [res.data.modelId]
      data.form.modelName = res.data.modelName
      data.form.bindTimes = res.data.bindTimesList.map((item) => {
        return {
          state: item.state,
          time: [item.startTime, item.endTime],
          startTime: item.startTime,
          endTime: item.endTime
        }
      })
    }
  })
}

const handleBindParamsDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      apiTemplate.deleteParamBind(record.id).then((res) => {
        if (res.code === 200) {
          Message.success('删除成功')
          getList()
        }
      })
    }
  })
}

const handleBindPrams = () => {
  data.bindVisible = true
  data.selectedKeys = []
  data.form = {
    runMode: 1,
    mode: 1,
    bindTimes: [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  }
}

const addTime = () => {
  data.form.bindTimes.push({
    state: 1,
    time: [],
    startTime: '',
    endTime: ''
  })
}

const deleteTime = (index) => {
  data.form.bindTimes.splice(index, 1)
}

const handleSelect = (rowKeys, rowKey, record) => {
  console.log(rowKeys, 'rowKeys')
  console.log(rowKey, 'rowKey')
  console.log(record, 'record')
  data.selectedKeys = rowKeys
  data.form.modelId = rowKey
  data.form.modelName = record.name
  if (record.conditionSet === 1) {
    data.templateFlag = 1
  } else if (record.conditionSet === 2) {
    data.templateFlag = 2
  } else {
    data.templateFlag = 3
  }
}

const handleBindParamsOk = (done) => {
  formRef.value.validate().then((col) => {
    console.log(data.form, 'data.form')
    data.form = {
      ...data.form,
      deviceId: props.deviceId
    }
    if (+data.form.mode === 1) {
      data.form.bindTimes = data.form.bindTimes.map((item) => {
        return {
          ...item,
          startTime: item.time[0],
          endTime: item.time[1]
        }
      })
    } else {
      delete data.form.bindTimes
    }
    data.form.parameterList = data.form.paramList.map((item) => {
      return {
        satId: item.satId,
        satCode: item.satCode,
        satName: item.satName,
        paramId: item.paramId,
        paramCode: item.paramCode,
        paramName: item.paramName,
        subsystemId: item.subsystemId,
        subsystemName: item.subsystemName,
        deviceId: item.deviceId,
        deviceCode: item.deviceCode,
        deviceName: item.deviceName
      }
    })
    // data.form.satId = props.currentSatellite.satId;
    // data.form.satId = data.form.parameterList[0].satId;
    // data.form.satCode = data.form.parameterList[0].satCode;
    // data.form.satName = data.form.parameterList[0].satName;

    data.form.satId = data.form.parameterList[0].satId
    data.form.satName = data.form.parameterList[0].satName
    data.form.satCode = data.form.parameterList[0].satCode
    data.form.subsystemId = data.form.parameterList[0].subsystemId
    data.form.subsystemName = data.form.parameterList[0].subsystemName
    data.form.deviceCode = data.form.parameterList[0].deviceCode
    data.form.deviceName = data.form.parameterList[0].deviceName
    console.log(data.form, 'data.form')
    if (!col) {
      const api = data.form.id ? apiTemplate.updateParamBind : apiTemplate.saveParamBind

      api(data.form).then((res) => {
        if (res.code === 200) {
          Message.success('绑定成功')
          data.bindVisible = false
          getList()
        } else {
          Message.error('绑定失败')
        }
      })
      done(true)
    } else {
      done(false)
    }
  })
}

const getModelList = () => {
  apiTemplate
    .getComplexModelList({
      pageNum: 1,
      pageSize: 100
    })
    .then((res) => {
      if (res.code === 200) {
        data.thresholdList = res.data.list
      }
    })
}

const handlePageChange = (page) => {
  data.pagination.pageStart = page
  getList()
}

const handlePageSizeChange = (size) => {
  data.pagination.pageLength = size
  getList()
}

watch(
  () => props.deviceId,
  () => {
    getList()
  }
)

const getList = () => {
  console.log(props.deviceId, 'props.deviceId')
  data.loading = true
  apiTemplate
    .getParamBindList(Object.assign(data.pagination, { deviceId: props.deviceId }))
    .then((res) => {
      if (res.code === 200) {
        data.loading = false
        data.tableData = res.data.list
        data.pagination.total = +res.data.total
      } else {
        data.loading = false
      }
    })
    .finally(() => {
      data.loading = false
    })
}

onMounted(() => {
  getModelList()
  getList()
})
</script>

<style scoped>
:deep(.arco-btn-size-small) {
  padding: 5px;
}
</style>
